package so.ifl.commons.tools.pinter.impl;

import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import so.ifl.commons.tools.DateUtil;
import so.ifl.commons.tools.DoradoSystemUtils;
import so.ifl.commons.tools.StringHelper;
import so.ifl.commons.tools.pinter.Iprinter;
import so.ifl.servcie.TransactionService;
import so.ifl.vo.AccountVo;
import so.ifl.vo.TranRecordVo;

/**
 *create by aaron.lu
 *create at 2012-5-20 下午2:22:55
 *<mailto: atyuan.lu@gmail.com>
 **/
public class Sum2Printer implements Iprinter{

Logger logger_ = LoggerFactory.getLogger(this.getClass());
	
	private String LIST_ = "list";
	private String TOTAL_ = "total";

	@Override
	public void print(Map<String, Object> data, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		logger_.debug("param:" + data);
		
		List<TranRecordVo> list = (List<TranRecordVo>)data.get(LIST_);
		Float total = (Float)data.get(TOTAL_);
		if (!(null != list && null != total)) {
			throw new Exception("nullpoint of tran_record info...");
		}
		
		int count = list.size();// 总记录数
		int pageCount = 36;// 每页记录数
		int page = 0;// 总共页数
		/** 主要控制总共的页数 */
		if (count >= pageCount && count % pageCount == 0) {//如果恰好整数
			page = count / pageCount;
		} else {//非整数
			page = count / pageCount + 1;
		}
		
		ByteArrayOutputStream baos[] = new ByteArrayOutputStream[page];// 用于存储每页生成PDF流
		
		String servletPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +request.getContextPath();
		String model_path = servletPath + "/templates/sum2.pdf";
		
		BaseFont baseFontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		
		int list_current = 0;//队列中被输出到pdf的序号
		
		for (int i = 0; i < page; i++) {
			PdfReader reader = new PdfReader(model_path);
			baos[i] = new ByteArrayOutputStream();
			PdfStamper pdfStamper = new PdfStamper(reader, baos[i]);
			
			AcroFields form = pdfStamper.getAcroFields(); 
			form.addSubstitutionFont(baseFontChinese);
			
			if (count % pageCount != 0 && i == page - 1) {//最后一页
				logger_.debug("====pageCount+" + pageCount + "=====");
				pageCount = count % pageCount;
			}
			 
			String printDate_ = request.getParameter("lessTime");
			
			form.setField("queryDate", printDate_ + "缴费情况");
			if (list.size() > 0) {//取第一条的收费来源
				form.setField("officeName", "来源:" + list.get(0).getTranOfficeName());
			}
			
			form.setField("title", "补考费缴费情况");

			form.setField("sum", total.toString());
			form.setField("printDate", DateUtil.YMD_SDF_POINT.format(new Date()));
			AccountVo accountVo = DoradoSystemUtils.getCurrentUser(request);
			if (null != accountVo) {
				form.setField("printUser", accountVo.getAccountOwner());
			}
			if (null != list && list.size() > 0 ) {
				form.setField("title", "补考费缴费情况");
				Float ssum = new Float(0);
				for (int j = 0; j < pageCount; j++) {
					if (j < list.size()) {
						TranRecordVo tranRecordVo = list.get(list_current++);
						int seq = (j + 1) + (j * 7);
						form.setField("fill_" + seq, (j + 1) + "");
						form.setField("fill_" + (seq + 1), tranRecordVo.getOfficeName());
						form.setField("fill_" + (seq + 2), tranRecordVo.getStudentName());
						form.setField("fill_" + (seq + 3), tranRecordVo.getStudentCertificateNumber());
						form.setField("fill_" + (seq + 4), tranRecordVo.getStudentPhone());
						form.setField("fill_" + (seq + 5), tranRecordVo.getItemType());
						form.setField("fill_" + (seq + 6), tranRecordVo.getMoney().toString());
						ssum = ssum + tranRecordVo.getMoney();
					}
					
				}
				form.setField("suml", ssum.toString());
			}
			pdfStamper.setFormFlattening(true); // 千万不漏了这句啊, */
			pdfStamper.close();
			
		}


		ServletOutputStream out = response.getOutputStream();
		Document document = new Document();
		PdfCopy copy = new PdfCopy(document, out);  
		document.open();
		response.setContentType("application/pdf");
		
		for (int t = 0; t < baos.length; t++) {
			logger_.info(baos[t].size() + " bytes has write to out..");
			document.newPage();
			PdfReader reader = new PdfReader(baos[t].toByteArray()); 
			PdfImportedPage pdfImportedPage = copy.getImportedPage(reader, 1);
			copy.addPage(pdfImportedPage);
			
//			baos[t].writeTo(out);
//			out.flush();						
//			
//			baos[t].close();
		}
		document.close(); 
		out.flush();
		out.close();
	}

	@Override
	public Map<String, Object> getData(HttpServletRequest request)
			throws Exception {
		ServletContext servletContext = request.getSession().getServletContext();		
		ApplicationContext appctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);;
		TransactionService transactionService = (TransactionService)appctx.getBean("transactionService");
		
		
		String lessTime = request.getParameter("lessTime");
		String biggerTime = request.getParameter("biggerTime");
		String officeCode = request.getParameter("officeCode");
		
		
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> params = new HashMap<String, Object>();
		
		
		
		
		if (StringHelper.isNotEmpty(lessTime) && StringHelper.isNotEmpty(officeCode)) {
			Date less_time = DateUtil.YMD_SDF.parse(lessTime);
			Date bigger_time = DateUtil.YMD_SDF.parse(biggerTime);
			
			if (null != less_time && null != bigger_time) {
				
				try {
					params.put("less_time_", DateUtil.getFirstSecondInDay(less_time));
					params.put("bigger_time", DateUtil.getLastSecondInDay(bigger_time));
					params.put("tran_office_code_", officeCode);
					params.put("is_charge_against_", "0");
					params.put("is_markup_", "1");
					params.put("type_of_tran_in_", "0");
					

				} catch (Exception e) {
					logger_.error("提取查询参数失败：" + e.getMessage());
				}
				
			}
			
			AccountVo accountVo = DoradoSystemUtils.getCurrentUser(request);
			if (null != accountVo && null !=  accountVo.getAccoutId()) {
				params.put("company_id", accountVo.getCompanyId());
				
				List<TranRecordVo> list = transactionService.queryTranInfo(params, 0, 100);
				Float total = transactionService.sumTranInfo(params);
				
				result.put(LIST_, list);
				result.put(TOTAL_, total);
			}
			
		}
		
		return result;
	}
}
